#include "my_uart.h"

volatile char uart_rx_buf[UART_BUF_LEN];
volatile uint8_t uart_rx_idx = 0;

void uart0_send_char(char ch)
{
    while( DL_UART_isBusy(UART_0_INST) == true );
    DL_UART_Main_transmitData(UART_0_INST, ch);
}
void uart0_send_string(char* str)
{
    while(*str!=0&&str!=0)
    {
        uart0_send_char(*str++);
    }
}
void uart0_printf(char* format, ...)
{
    char buffer[128];
    va_list args;
    va_start(args, format);
    vsnprintf(buffer, sizeof(buffer), format, args);
    va_end(args);
    uart0_send_string(buffer);
}
void parse_uart_command(char *input, PID *PID_param)
{
    uart0_printf("Received: %s\r\n", input); // 调试输出
    char temp[64];
    strncpy(temp, input, sizeof(temp));
    temp[sizeof(temp) - 1] = '\0';

    char *cmd = strtok(temp, " \r\n");
    if (cmd == NULL) return;

    if (strcmp(cmd, "PID") == 0)
    {
        char *kp_str = strtok(NULL, " \r\n");
        char *ki_str = strtok(NULL, " \r\n");
        char *kd_str = strtok(NULL, " \r\n");
        if (kp_str && ki_str && kd_str)
        {
            PID_param->Kp = atof(kp_str);
            PID_param->Ki = atof(ki_str);
            PID_param->Kd = atof(kd_str);
            uart0_printf("PID set: Kp=%.2f Ki=%.2f Kd=%.2f\r\n", PID_param->Kp, PID_param->Ki, PID_param->Kd);
        }
        else
        {
            uart0_printf("Format: PID kp ki kd\r\n");
        }
    }
    else if (strcmp(cmd, "SPD") == 0)
    {
        char *spd_str = strtok(NULL, " \r\n");
        if (spd_str)
        {
            PID_param->SetValue = atof(spd_str);
            uart0_printf("SPD set: %.2f\r\n", PID_param->SetValue);
        }
        else
        {
            uart0_printf("Format: SPD value\r\n");
        }
    }
    else
    {
        uart0_printf("Unknown CMD!\r\n");
    }
}